package com.lune.blog.system.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lune.blog.base.domain.system.SysMenu;
import com.lune.blog.base.domain.system.SysRoleMenu;
import com.lune.blog.base.domain.system.SysUser;
import com.lune.blog.system.mapper.MenuMapper;
import com.lune.blog.system.mapper.RoleMenuMapper;
import com.lune.blog.system.service.MenuService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author yanjizhw@163.com
 * @date 2021/11/18 20:38
 * 描述: 菜单业务
 * @since 1.0.0
 */
@Service("menuService")
public class MenuServiceImpl extends ServiceImpl<MenuMapper, SysMenu> implements MenuService   {

    @Resource
    private UserRoleServiceImpl userRoleService;

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Override
    public Set<String> getMenuPermission(Long userId) {

        Set<String> perms = new HashSet<String>();
        if (SysUser.isAdmin(userId)) {
            perms.add("*:*:*");
        }
        List<Long> roleIds = userRoleService.getRoleIdsByUserId(userId);
        List<SysRoleMenu> roleMenus = roleMenuMapper.selectList(new QueryWrapper<SysRoleMenu>().in("role_id", roleIds));
        List<Long> menuIds = roleMenus.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
        List<SysMenu> menus = baseMapper.selectList(new QueryWrapper<SysMenu>().in("menu_id", menuIds));
        for (SysMenu menu: menus) {
            if (ObjectUtil.isNotNull(menu)) {
                perms.addAll(Arrays.asList(menu.getPerms().trim().split(",")));
            }
        }
        return perms;
    }
}
